package com.bdqn.demo.servlet;

import com.bdqn.demo.pojo.Role;
import com.bdqn.demo.pojo.User;
import com.bdqn.demo.service.UserService;
import com.bdqn.demo.service.impl.UserServiceImpl;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/register")
public class InsertServlet extends HttpServlet {
    UserService userService=new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Role> list=userService.getRoleName();
        req.setAttribute("roleName",list);
        req.getRequestDispatcher("register.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        UserService userService=new UserServiceImpl();
        int roleId=Integer.parseInt(req.getParameter("roleName"));
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        Integer result1=userService.registerIf(username);
        if(result1==null){
            User user=new User();
            user.setRoleId(roleId);
            user.setUsername(username);
            user.setPassword(password);
            userService.addUser(user);
            req.setAttribute("error","注册成功");
            req.getRequestDispatcher("index.jsp").forward(req,resp);
        }
        req.setAttribute("error","注册失败");
        this.doGet(req,resp);
    }
}

